<?php
$antDir = $argv[1];
$finalDir = $argv[2];
$filename = $argv[3];


$file = $finalDir.'/css/pictolemmes.css';

$lines = file($file);
foreach ($lines as $key => $line) {
  if (preg_match('/url\(\'images.*\'\)/i',$line)) {
    $css = preg_replace('/^.*url\(\'images\/(.*)\'\).*$/','\\1',$line);
    $file = new Caffeine_View_Helper_ImageBase64($finalDir.'/css/images/'.trim($css));
    $lines[$key] = preg_replace('/url\((.*)\)/','url('.$file.')',$lines[$key]);
  }
}

$writefile =  $finalDir.'/css/'.$filename;
file_put_contents($writefile, $lines);
echo "Base64 Done\n";

class Caffeine_View_Helper_ImageBase64 {
  public function __construct($image) {
	$this->_file = $image;
    $fp = fopen($this->_file,'rb', 0);
    if (!$fp) throw new Exception('Could not open '.$this->_file.' for reading');
    $picture = fread($fp,filesize($this->_file));
    fclose($fp);
    $this->_encoded = base64_encode($picture);
  }
  
  public function output() {
	// php.ini : activer extension=php_fileinfo.dll
  	$finfo = finfo_open(FILEINFO_MIME_TYPE); 
    return 'data:'.finfo_file($finfo, $this->_file).';base64,'.$this->_encoded;
  }
  
  public function __toString() {
    return $this->output();
  }
}